package com.sp.fresh_produce.web;

import com.sp.fresh_produce.ex.CustomException;
import com.sp.fresh_produce.ex.ExceptionCodeEnum;
import com.sp.fresh_produce.model.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 管理员权限拦截器
 * <p>
 * 拦截带有 {@link AdminRequired} 的请求，校验会话中是否存在已登录管理员用户。
 */
@Component
public class AdminRequiredInterceptor implements HandlerInterceptor {

    private static final String USER_SESSION_KEY = "user";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod handlerMethod)) {
            return true;
        }

        AdminRequired adminRequired = handlerMethod.getMethodAnnotation(AdminRequired.class);
        if (adminRequired == null) {
            adminRequired = handlerMethod.getBeanType().getAnnotation(AdminRequired.class);
        }
        if (adminRequired == null) {
            return true;
        }

        User user = (User) request.getSession().getAttribute(USER_SESSION_KEY);
        if (user == null) {
            throw new CustomException(ExceptionCodeEnum.NOT_LOGIN);
        }
        Integer role = user.getRole();
        if (role == null || role != 2) {
            throw new CustomException(ExceptionCodeEnum.FORBIDDEN);
        }
        return true;
    }
}


